/*
 * This file is Copyright 2002-2006 Loyola University Chicago,
 * Department of Computer Science and the Emerging Technologies Laboratory.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License via
 *    http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.citep.web.admin.users.client;

import java.util.HashMap;

import com.citep.web.gwt.dto.UserDTO;
import com.citep.web.gwt.module.BasePresentation;
import com.citep.web.gwt.module.Presentation;
import com.citep.web.gwt.validators.EmailValidator;
import com.citep.web.gwt.validators.RequiredValidator;
import com.citep.web.gwt.validators.ValidatorGroup;
import com.citep.web.gwt.widgets.StatusLabel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class UserLoginPresentation extends BasePresentation implements Presentation  {
	UserLoginApplication application;

	protected Grid inputGrid;
	protected Button submitButton;
	protected StatusLabel statusLabel;
	protected StatusLabel errorLabel;

	private TextBox emailText;
	private PasswordTextBox passwordText;
	
	protected VerticalPanel mainPanel;
	
	protected HashMap errorLabels = new HashMap();
	protected ValidatorGroup validator;

	protected ClickListener loginAction; //save account submit action
	
	public void clearFields() {
		passwordText.setText("");
	}
	
	public void setWaitState() {
		getStatusLabel().setText("Wait...");
		getStatusLabel().setVisible(true);
		clearFields();
		clearErrors();
		
		submitButton.setText("Wait...");
		submitButton.setEnabled(false);
	}
	
	public void clearErrors() {
		super.clearErrors();
		getErrorLabel().hide();
	}
	
	public void setReadyState() {
		getStatusLabel().hide();
		clearErrors();
		submitButton.setText("Log In");
		submitButton.setEnabled(true);
	}
	

	public void getUserData(UserDTO user) {
		if(user != null) {
			user.setEmail(emailText.getText());
			user.setPassword(passwordText.getText());
		}
	}
	
	public StatusLabel getStatusLabel() {
		if(statusLabel == null) {
			statusLabel = new StatusLabel();
			statusLabel.setStyleName("status_label_small");
			statusLabel.setVisible(false);
		}

		return statusLabel;
	}

	public StatusLabel getErrorLabel() {
		if(errorLabel == null) {
			errorLabel = new StatusLabel();
			errorLabel.setStyleName("error_label_big");
			errorLabel.setVisible(false);
		}

		return errorLabel;
	}

	
	
	public void addWidgetToInputGrid(Grid g, String description, Widget w) {
		int rows = g.getRowCount();
		int cols = g.getColumnCount();
		
		g.resize(rows+1,cols);
		g.setText(rows, 0, description);
		g.setWidget(rows,1, w);
		g.getCellFormatter().setStyleName(rows, 0, "input_cell");
		g.getCellFormatter().setStyleName(rows, 1, "input_cell");

	}
		
	public void displayStatus(String text, int seconds) {
		getStatusLabel().setText(text);
		getStatusLabel().show(seconds);
	}
	
	public void displayError(String msg) {
		getErrorLabel().setText(msg);
		getErrorLabel().setVisible(true);
	}
	
	protected Button getSubmitButton() {
		if(submitButton == null) {
			submitButton = new Button("Log In");
			submitButton.setStyleName("form_button");
			submitButton.addClickListener(new ClickListener() {
				public void onClick(Widget w) {
					clearErrors();
					if(validator.validate()) {
						application.authenticate(emailText.getText(), passwordText.getText());
					}
				};
			});
		}
		
		return submitButton;
	}
	
	
	public Widget getContext() {
		return null;
	}

	public Widget getMainPanel() {
		return mainPanel;
	}

	public void setApplication(UserLoginApplication application) {
		this.application = application;
	}

	public Grid getInputGrid() {
		if(inputGrid == null) {
			inputGrid = new Grid(0,2);
			inputGrid.setCellPadding(0);
			inputGrid.setCellSpacing(0);
			
			inputGrid.setStyleName("input_grid");
			
			addValidationLabelToGrid(inputGrid, createErrorLabel("User.email"));
			
			emailText = createTextBox("form_textentry", 30);
			addWidgetToInputGrid(inputGrid, "Email:", emailText);
			
			addValidationLabelToGrid(inputGrid, createErrorLabel("User.password"));
			
			passwordText = createPasswordTextBox("form_textentry",10);
			addWidgetToInputGrid(inputGrid, "Password:", passwordText);

			int rows = inputGrid.getRowCount();
			int cols = inputGrid.getColumnCount();
			
			inputGrid.resize(rows+1,cols);
		}
		
		setValidation();
		return inputGrid;
	}

	
	public void setValidation() {
		if(validator == null)
			validator = new ValidatorGroup();
		
		ValidationErrorListener listener = new ValidationErrorListener();
		
		validator.addValidator("User.email", emailText, new RequiredValidator(listener,"Please enter a valid email"));
		validator.addValidator("User.password", passwordText, new RequiredValidator(listener,"Please enter a valid password"));
		validator.addValidator("User.email", emailText, new EmailValidator(listener, "Please enter a valid email"));
	}

		
	public UserLoginPresentation() {
		mainPanel = new VerticalPanel();
		mainPanel.setWidth("100%");
		
		getTitleLabel().setText("Log in");
		mainPanel.add(getTitlePanel());
		
		mainPanel.add(getInputGrid());
		mainPanel.setCellHorizontalAlignment(getInputGrid(), HasHorizontalAlignment.ALIGN_CENTER);
		
		mainPanel.add(getSubmitButton());
		mainPanel.setCellHorizontalAlignment(getSubmitButton(), HasHorizontalAlignment.ALIGN_CENTER);

		getTitlePanel().setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		getTitlePanel().add(getStatusLabel());
	
		mainPanel.add(getErrorLabel());
		mainPanel.setCellHorizontalAlignment(getErrorLabel(), HasHorizontalAlignment.ALIGN_CENTER);
	}

}
